<script setup>
import { useUserStore, usePaintingStore } from "@/store";
import { ref, watch, withCtx } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import eliminateBtn from "./child/eliminateBtn.vue";
import SwitchHistory from "@/draw/components/SwitchHistory.vue";
import { imgInpaint, resultImgUpload, getImageByTaskId } from "@/api/painting";
import { getImageByTask } from "@/utils/canvasHelp.js";
import { imgUploadVerify } from "@/utils/auth";
import Toast from "@vant/weapp/dist/toast/toast";
import MyCanvas from "@/utils/myCanvas/index.js";
import Brush from "../components/Brush.vue";
import Compare from "../components/Compare.vue";

const userStore = useUserStore();
const paintingStore = usePaintingStore();
const expireVipModal = ref(false);
const isBtnShow = ref(true);
let textCanvas;
const touchStartX = ref(0);
const touchStartY = ref(0);
const eliminateBtnRef = ref(null);
let canvas = null,
  ctx = null;
let bgImgList = [];
let activeDefault = -1;
let bgImgListRef = ref([]); // 这个是传给子组件用

let bg = null,
  dpr = 1;
let userImgPath = ref(""); // 用户插入的图片的路径
let destinationX = ref(0);
let destinationY = ref(0);
let reImg = null;
let isPrev = ref(false);
let cWidth = 0,
  cHeight = 0; // canvas的宽，高
let dWidth = ref(0),
  dHeight = ref(0); //目标canvas的宽，高
let sWidth = 0,
  sHeight = 0; // 用户插入的图片的宽高
let status = ref(-10); // -1未开始，0: 合成前 1.已完成合成图片，用户已上传图片，2用户点击确认，3用户点击对比
let composeImg = ref({});
let isLoadingShow = ref(false);
let lineWidth = ref(10);
let isDownload = ref(false);
let myCanvas = null;
const item = ref({});
let activeIndex = ref(activeDefault);
onLoad((e) => {
  item.value = JSON.parse(e.item);
  // operate3();
});
let isTumo = false; // 用户是否涂抹过
/**
 * @description 用户上传图片
 * @param {*} result
 */
const canvasDrawFn = (result) => {
  uni
    .createSelectorQuery()
    .select("#maskCanvas")
    .fields({ node: true, size: true })
    .exec((res) => {
      console.log("canvasDrawFn");
      cWidth = res[0].width;
      cHeight = res[0].height;
      dWidth.value = res[0].width;
      canvas = res[0].node;
      textCanvas = res[0].node;
      ctx = canvas.getContext("2d");

      dpr = uni.getSystemInfoSync().pixelRatio;
      const imgWidth = result.width / dpr;
      const imgHeight = result.height / dpr;

      canvas.width = cWidth * dpr;
      canvas.height = cHeight * dpr;
      ctx.scale(dpr, dpr);
      myCanvas = new MyCanvas({
        canvas: canvas,
        width: 300,
        editMode: "eliminate",
        cWidth: canvas.width,
        cHeight: canvas.height,
      });

      myCanvas.ctx.lineWidth = lineWidth.value;
      // ctx.clearRect(0, 0, canvas.width, canvas.height)
      // ctx.beginPath();
      bg = canvas.createImage();
      reImg = canvas.createImage();
      bg.src = result.path;
      status.value = -1;
      bgImgList = [];
      bgImgListRef.value = [];
      activeIndex.value = activeDefault;
      composeImg.value = {};
      bg.onload = (bgObj) => {
        sWidth = bg.width;
        sHeight = bg.height;

        dHeight.value = (cWidth / bg.width) * bg.height;
        // 如果它属于特别高的
        if (cHeight - dHeight.value < 0) {
          dHeight.value = cHeight;
          dWidth.value = (cHeight / bg.height) * bg.width;
          destinationY.value = 0;
          destinationX.value = (cWidth - dWidth.value) / 2;
        } else {
          destinationX.value = 0;
          destinationY.value = (cHeight - dHeight.value) / 2;
        }

        userImgPath.value = result.path;
        updateHistoryRecord({
          userPath: result.path,
        });
      };
      isBtnShow.value = false;
    });
};
let bgImagePath = ref("");
watch(userImgPath, () => {
  bgImagePath.value = userImgPath.value;
});
// watch(composeImg, () => {
//   bgImagePath.value = composeImg.value.imgPath;
// });
// function setBrushSize(size) {
//   let newBrush = size * 2;
//   myCanvas.ctx.lineWidth = newBrush == 0 ? 1 : newBrush;
//   // this.lineWidth =
// }
watch(activeIndex, () => {
  if (activeIndex.value > -1) {
    // if (activeIndex.value == 0) {
    //   ctx.clearRect(0, 0, canvas.width, canvas.height);
    //   return;
    // }
    let activeObj = bgImgListRef.value[activeIndex.value];
    let { composePath, userPath, maskPath } = activeObj;
    let newBgPath = "";
    if (userPath && !maskPath) {
      console.log("144");
      newBgPath = userPath;
    } else if (!userPath && !maskPath && composePath) {
      console.log("147");
      // 如果当前最新的是一张合成图
      newBgPath = composePath;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    } else if (userPath && maskPath) {
      console.log("152");
      newBgPath = userPath;
    }
    console.log("背景图", newBgPath);

    if (bgImagePath.value == newBgPath) return;
    bgImagePath.value = newBgPath;
  }
});
function cancel() {
  isTumo = false;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  bgImgListRef.value.length = 1;
  bgImgList.length = 1;
  activeIndex.value = 0;
  status.value = 0;
}
const onClickBtnFn = async () => {
  const url = await imgUploadVerify();

  const res3 = await uni.getImageInfo({
    src: url,
  });
  isTumo = false;

  canvasDrawFn(res3);
};

const touchstartFn = (e) => {
  if (!myCanvas) return;
  myCanvas.touchStart(e);
};

const touchmoveFn = (e) => {
  // let newBrush = eliminateBtnRef.value?.brushSize * 2;
  // myCanvas.ctx.lineWidth = newBrush == 0 ? 1 : newBrush;
  myCanvas.touchMove(e);
};
const touchEndFn = async (e) => {
  if (!bgImagePath.value) return;
  // myCanvas.touchEnd();
  let obj = {
    canvas,
    x: destinationX.value,
    y: destinationY.value,
    width: dWidth.value, // sWidth,
    height: dHeight.value, // sHeight,
    destWidth: sWidth,
    destHeight: sHeight,
  };
  console.log("obj", obj);
  const res = await uni.canvasToTempFilePath(obj);
  isTumo = true;
  updateHistoryRecord({
    userPath: bgImagePath.value,
    maskPath: res.tempFilePath,
  });
};
/**
 * @description 添加一条历史记录
 * @param {String} imgPath 当前要添加的图片的本地记录
 */
function updateHistoryRecord({ userPath, maskPath, composePath, type }) {
  // activeIndex.value = activeIndex.value + 1;
  bgImgList.push(maskPath);
  let insertObj = {
    userPath,
    maskPath,
    composePath,
    type,
  };
  bgImgListRef.value.push(insertObj);
  activeIndex.value = bgImgListRef.value.length - 1;
  console.log("插入的记录-userPath", userPath);
  console.log("插入的记录-maskPath", maskPath);
  console.log("插入的记录-composePath", composePath);
}
/**
 * @description 下载图片
 */
async function downloadImage() {
  let localImgObj = await paintingStore.urlSaveImgFn(
    composeImg.value.sourceImgPath
  );
}
/**
 * @description 一键消除，移除抠图部分
 */
function removeMask(e) {
  let error = "";
  if (!userImgPath.value) {
    error = "你还没有上传图片";
  } else if (!isTumo) {
    error = "你还没有涂抹";
  }
  //  else if (!(bgImgListRef.value[activeIndex.value].maskPath)) {
  //   error = '你还没有重新涂抹';
  // }
  if (error) {
    Toast.fail(error);
  } else {
    if (e) return (expireVipModal.value = e);
    // 先上传两张图片
    uploadImage();
  }
}
/**
 * @description 上传图片
 */
async function uploadImage() {
  try {
    isLoadingShow.value = true;
    console.log("背景图", bgImagePath.value);
    // 上传背景图
    let userImg = await paintingStore.imageUploadFile({
      tempFilePath: bgImagePath.value,
      formData: {
        type: 4,
      },
    });
    // 上传遮罩图
    let maskImg = await paintingStore.imageUploadMaskFile(
      bgImgListRef.value[activeIndex.value].maskPath,
      {
        orgImgUrl: userImg,
      }
    );

    let removeRes = await imgInpaint({
      imageFileUrl: userImg,
      imageMaskFileUrl: maskImg,
    });
    console.log("返回的东西", userImg, maskImg, removeRes);
    // setTimeout(() => {
    //   getImageByTaskIdFn(removeRes.data.taskId);
    // }, 8000);
    let res = await getImageByTask({ taskId: removeRes.data.taskId });
    if (res.data.state != 1) {
      isLoadingShow.value = false;
      return;
    }

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // userImgPath.value = res.data.imgPath;
    isLoadingShow.value = false;
    // let imgLocalPath = await paintingStore.urlSaveImgFn(res.data.imgPath);
    if (!res.data.imgPath) {
      return Toast.fail("消除失败");
    }

    console.log("res.data.imgPath", res.data.imgPath);
    isTumo = false;
    const imgLocalObj = await uni.getImageInfo({
      src: res.data.imgPath,
    });

    res.data.sourceImgPath = res.data.imgPath;
    status.value = 1;
    res.data.imgPath = imgLocalObj.path;
    reImg.src = imgLocalObj.path;
    bgImagePath.value = imgLocalObj.path;
    updateHistoryRecord({
      composePath: imgLocalObj.path,
    });
    // bgImgListRef.push({ composePath: imgLocalObj.path })
    // if(reImg.src==composeImg.value.src){

    // }
    // reImg.onload = function () {
    //   ctx.clearRect(0, 0, canvas.width, canvas.height);
    //   ctx.drawImage(reImg, destinationX.value, destinationY.value, dWidth.value, dHeight.value);

    // }

    composeImg.value = res.data;
  } catch (error) {
    isLoadingShow.value = false;
  }
}
async function getImageByTaskIdFn(taskId) {
  let res = await getImageByTaskId(taskId);
  // uni.showToast({ title: '保存成功' })
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // userImgPath.value = res.data.imgPath;
  isLoadingShow.value = false;
  // let imgLocalPath = await paintingStore.urlSaveImgFn(res.data.imgPath);
  if (!res.data.imgPath) {
    return Toast.fail("消除失败");
  }

  console.log("res.data.imgPath", res.data.imgPath);
  const imgLocalObj = await uni.getImageInfo({
    src: res.data.imgPath,
  });

  res.data.sourceImgPath = res.data.imgPath;
  status.value = 1;
  res.data.imgPath = imgLocalObj.path;
  reImg.src = imgLocalObj.path;
  bgImagePath.value = imgLocalObj.path;
  isTumo = false;
  updateHistoryRecord({
    composePath: imgLocalObj.path,
  });
  // bgImgListRef.push({ composePath: imgLocalObj.path })
  // if(reImg.src==composeImg.value.src){

  // }
  // reImg.onload = function () {
  //   ctx.clearRect(0, 0, canvas.width, canvas.height);
  //   ctx.drawImage(reImg, destinationX.value, destinationY.value, dWidth.value, dHeight.value);

  // }

  composeImg.value = res.data;
}
function setBrushSize(brush) {
  console.log("设置canvasbrush", brush);
  myCanvas.brushSize = brush;
}
const eliminateFn = (e) => {
  removeMask(e);
};
/**
 * @description 上一步下一步
 * @param {*} type
 */
async function operate({ index, type, imgPath }) {
  activeIndex.value = index;
  console.log("eliminate~operate~activeIndex", activeIndex.value);
  const { maskPath, composePath } = imgPath;
  if (!maskPath && !composePath) {
    console.log("eliminate~operate~clear");
    isTumo = false;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    return;
  } else {
    console.log("eliminate~operate~不是清楚图片", 346);
    isTumo = true;
    // if (wantImg) {
    const res3 = await uni.getImageInfo({
      src: imgPath.maskPath,
    });

    reImg.src = res3.path;
    // if(reImg.src==composeImg.value.src){

    // }
    reImg.onload = function () {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(
        reImg,
        destinationX.value,
        destinationY.value,
        dWidth.value,
        dHeight.value
      );
    };
  }
  console.log("refimage", bgImgListRef);
  // }
  // canvasDrawFn(res3)
}
function confirm() {
  let isRemove = false;
  let lastItem = bgImgListRef.value[activeIndex.value];
  if (lastItem.composePath) {
    status.value = 2;
  } else {
    wx.showToast({
      title: "你还没有消除",
      icon: "none",
    });
  }
}
function compare(val) {
  status.value = val;
}
// let isNormalShow = computed(() => {
//   return status.value > -10 && status.value < 2 ? true : false;
// })
</script>

<template>
  <NavBar>AI消除</NavBar>
  <Loading v-model:isLoadingShow="isLoadingShow" :timer="100"></Loading>
  <ExpireVipModal v-model:expireVipModal="expireVipModal"></ExpireVipModal>
  <div class="draw-image" style="position: relative">
    <!-- active::{{activeIndex}}  bgImgListRef.length:{{ bgImgListRef.length }}
    当前:{{ bgImgListRef[activeIndex] }} -->
    <!-- active:{{ activeIndex }} -->
    <!-- <image v-if="composeImg.imgPath" :src="composeImg.imgPath" :style="{

      width: cWidth
        + 'px', height: dHeight + 'px', marginTop: destinationY + 'px'
    }" class="draw compose-img" /> -->
    <!-- status:{{ status }} -->
    <!-- bgImagePath:{{ bgImagePath }} -->
    <div v-show="status <= 3" style="position: relative">
      <image :src="bgImagePath" style="" class="draw" :style="{
        width: dWidth + 'px',
        height: dHeight + 'px',
        marginLeft: destinationX + 'px',
        marginTop: destinationY + 'px',
      }" />
      <canvas v-show="status < 2" style="width: 100%" disable-scroll="true" type="2d" id="maskCanvas" class="canvas draw"
        @touchstart="touchstartFn" @touchmove="touchmoveFn" @touchend="touchEndFn">
        <van-button v-if="isBtnShow" icon="iconfont ai-icon-xiangcexuanze" @click="onClickBtnFn">点击选择</van-button>

        <div v-else class="compareBox" @click="onClickBtnFn">
          <i class="iconfont ai-icon-zhongxinshengcheng"></i>
          <p>重新上传</p>
        </div>
      </canvas>
    </div>
    <!-- status:{{ status }}原图:{{ userImgPath }},现在的图:{{ composeImg.imgPath }} -->
    <div>
      <Compare v-if="status == 3" :imgUrl="composeImg.imgPath" :orgImage="userImgPath"></Compare>
    </div>
  </div>
  <van-toast id="van-toast"></van-toast>
  <div class="box fixed">
    <SwitchHistory v-if="status > -10 && status < 2" :imgRecordList="bgImgListRef" ref="eliminateBtnRef"
      @operate="operate" @downloadImage="downloadImage" @removeMask="removeMask" @cancel="cancel" @confirm="confirm"
      @compare="compare">
    </SwitchHistory>
    <div>
      <div class="saveImage-header-right" v-if="isDownload" @click="compare">
        <i class="iconfont ai-icon-qianhouduibi"></i>
        <p class="contrast">对比</p>
      </div>
      <Brush v-if="status > -10 && status < 2" :min="2" @setBrushSize="setBrushSize"></Brush>
      <myButton v-if="status <= 1" :id="item.id" @click="eliminateFn">AI消除</myButton>
      <div class="btn save" v-else @click="downloadImage">保存图片</div>
    </div>
    <!-- <eliminateBtn :bgImgList="bgImgListRef" :active="active" ref="eliminateBtnRef" @setBrushSize="setBrushSize"
        :status="status" @downloadImage="downloadImage" @removeMask="removeMask" @cancel="cancel" @confirm="confirm"
        @compare="compare">
      </eliminateBtn> -->
  </div>

  <van-toast id="van-toast"></van-toast>
</template>

<style lang="less" scoped>
/deep/.btnBox {
  margin-top: 40rpx !important;
}

// /deep/.btnBox {
//   margin-bottom: 20rpx !important;
// }

.draw-image,
.canvas {
  height: 1014rpx;
}

.draw-image {
  width: 690rpx;
  margin: 20rpx auto 0;
  background-color: var(--a-main-box-bg-color);
  border-radius: 20rpx;
  overflow: hidden;
}

.saveImage-header-right {
  flex: 1;
  text-align: right;
  color: #fff;

  .iconfont {}

  .contrast {
    font-size: 18rpx;
  }
}

.draw {
  position: absolute;
  left: 0;
  top: 0;
}

.canvas {
  width: 690rpx;
  border-radius: 20rpx;
  overflow: hidden;
  position: relative;
  z-index: 1;

  /deep/ .van-button {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 228rpx;
    height: 84rpx;
    border-radius: 45rpx;
    background-color: transparent;
    border: 3rpx solid var(--a-main-color);
    color: var(--a-one-text-color);
  }

  .compareBox {
    position: absolute;
    bottom: 20rpx;
    right: 20rpx;
    box-sizing: border-box;
    width: 80rpx;
    height: 80rpx;
    padding: 14rpx 0;
    background: rgba(0, 0, 0, 0.65);
    border-radius: 50%;
    font-size: 15rpx;
    color: #fff;
    text-align: center;
    z-index: 2000;
  }
}

/deep/.van-slider__bar {
  background-color: var(--a-main-color);
}

/deep/.van-slider__bar {
  background-color: var(--a-main-color);
}

.fixed {
  box-sizing: border-box;
  position: fixed;
  bottom: 0;
  width: 100%;
  padding: 30rpx 40rpx 30rpx;
  background-color: var(--a-main-tabNav-bg-color);

  .brush {
    display: flex;
    align-items: center;
    margin-top: 32rpx;

    .text {
      font-size: 26rpx;
      color: var(--a-two-text-color);
      margin-right: 20rpx;
    }

    .slider {
      flex: 1;
    }
  }

  .btn {
    box-sizing: border-box;
    width: 600rpx;
    height: 86rpx;
    border-radius: 44rpx;
    text-align: center;
    background: var(--a-main-color);
    color: var(--a-one-text-color);
    padding: 5rpx 0 0;
    margin: 25rpx auto 0;

    &.save {
      line-height: 86rpx;
    }

    .text {
      font-size: 32rpx;
    }

    .one {
      font-size: 20rpx;
    }
  }
}

.box {
  background: var(--a-main-tabNav-bg-color);
  height: 360rpx;

  .desc {
    margin-top: 20rpx;
    text-align: center;
    font-size: 24rpx;
    color: var(--a-one-text-color);
    letter-spacing: 0.5rpx;
  }
}
</style>
